import React, { Component } from 'react';
import { connect } from 'react-redux';
import SearchArea from 'components/search-area.js';
import SlideFrame from 'components/slide-frame';
import { Button } from 'antd';
import ResizeTable from 'components/resize-table';
import {messages} from 'share/common';
import config from 'config';
import CheckCenterImporter from 'containers/financial-management/check-center/check-center-importer';
import SupplierUtil from '../overview/supplierUtil';
import NewConsumerServer from './new-consumer-server';

class ConsumerOpenDetail extends Component {

  constructor(props) {
    super(props);
    this.state = {
      searchForm: props.searchForm,
      loading: false,
      asyncBtn: false,
      columns: props.columns,
      pagination: {
        current: 1,
        pageSize: 6,
        total: 0,
      },
      showImportFrame: false,
      isEdit: false,
      editData: {}, // 编辑数据
      data: [],
      errorColumns: SupplierUtil.exportErrorColumns()
    };
    this.service = NewConsumerServer(this)[props.service];
  }

  componentWillMount() {
    this.initListData();
  }

  initListData = () => {
    const { pagination } = this.state;
    this.service(pagination);
  };

  onSearch = (values) => {
    const { pagination } = this.state;
    pagination.current = 1;
    this.service({ ...pagination, ...values});
  };

  onClear = () => {
    const { pagination } = this.state;
    pagination.current = 1;
    this.setState({ pagination }, this.initListData);
  };

  onChangePager = (pagination) => {
    this.setState({ pagination }, () => {
      this.service(pagination);
    });
  };

  // 导入配置
  onInSetting = () => {
    this.showImport(true);
  };

  // 导出配置
  onOutSetting = () => {
    const { type } = this.props;
    NewConsumerServer(this).exportSettingData(type).then((res) => {
      window.open(res.data.exportFileRecord.tempUrl);
    });
  };

  // 下载模板回调
  templateDownload = (res) => {
    window.open(res.data.path);
  };

  onTableRow = (record, EditFrame, index) => {
    const { data } = this.state;
    this.setState({ isEdit: true, editData: EditFrame.getEditData(record, data, index) });
  };

  closeSlide = () => {
    this.refs.form.form.onCancelEdit();
  };

  afterCloseSlide = (isUpdate) => {
    this.setState({ isEdit: false, editData: {} });
    isUpdate === true && this.initListData();
  };

  afterCloseImport = () => {
    this.showImport(false);
    this.initListData();
  };

  showImport = (flag) => {
    this.setState({ showImportFrame: flag });
  };

  importResult = (res, type) => {
    switch (type) {
      case 'result': return res.data;
      case 'errorData': return res.data.errorList || res.data.failList;
    }
  };

  render() {
    const {
      searchForm, showImportFrame, loading, columns,
      pagination, data, isEdit, editData, errorColumns
    } = this.state;
    const { EditFrame, type } = this.props;
    return (
      <div>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.onSearch}
          clearHandle={this.onClear}
        />
        <div style={{ display: 'flex', justifyContent: 'space-between', margin: '20px 0' }}>
          <div>
            <Button type="primary" onClick={this.onInSetting}>
              {messages('supplier.key306')/* 导入配置 */}
            </Button>
            &nbsp;&nbsp;
            <Button onClick={this.onOutSetting}>
              {messages('supplier.key307')/* 导出配置 */}
            </Button>
          </div>
        </div>
        <ResizeTable
          rowKey={(record) => JSON.stringify(record)}
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={pagination}
          onChange={this.onChangePager}
          onRow={(record, index) => ({
            onClick: () => this.onTableRow(record, EditFrame, index)
          })}
          bordered
        />
        <SlideFrame
          show={isEdit}
          hasFooter={false}
          content={EditFrame}
          params={editData}
          onClose={this.closeSlide}
          title={editData.companyName || messages('common.edit')/* 编辑 */}
          afterClose={this.afterCloseSlide}
          ref="form"
        />
        <CheckCenterImporter
          visible={showImportFrame}
          title={messages('common.import')/* '导入' */}
          templateUrl={`${config.baseUrl}/api/vendors/service/import/template?vendor=${type === 'meiya' ? '' : type}`}
          templateMethod="get"
          templateCallBack={this.templateDownload}
          resultCallBack={this.importResult}
          errorColumns={errorColumns}
          uploadUrl={`${config.baseUrl}/api/vendors/service/import?vendor=${type === 'meiya' ? '' : type}`}
          fileName="Reconciliation Template"
          onOk={() => this.showImport(false)}
          isDownloadError
          downloadErrorUrl={`${config.baseUrl}/api/vendors/service/error/export`}
          descUpload={[messages('supplier.key308')/* 4.导入完成前，请勿关闭此窗口! */]}
          afterClose={this.afterCloseImport}
        />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {};
}

export default connect(mapStateToProps)(ConsumerOpenDetail);
